import { computed, defineComponent, nextTick, ref, toRefs } from 'vue'
import $style from './index.module.scss'

export default defineComponent({
    name : 'RadioOptions',
    props : {
        modelValue : {
            type : [String, Number],
            default : ''
        },

        options : {
            type: [Array, Object],
            default() {
                return []
            }
        },

        valueField : {
            type : String,
            default : 'value'
        },

        labelField : {
            type : String,
            default : 'label'
        }
    },

    setup(props:{options:any[] | { [key : string]:any } | { [key : number]:any }, valueField?:any, labelField?:any, modelValue?: string | number | undefined | null}, context) {
        let checkedVal = ref(props.modelValue) //初始值

        const { valueField, labelField, options } = toRefs(props)
        const optionsList = computed(() => {
            if(Array.isArray(options.value)) {
                return options.value
            }


            let optionsList:any[] = []
            for(let k in options.value) {
                optionsList.push({[valueField.value] : k, [labelField.value] : options.value[k]})
            }

            return optionsList

        })

        function change(value) {
            checkedVal.value = value
            context.emit('update:modelValue', value)
            nextTick(() => {
                context.emit('change', value)
            })
            
        }

        return () => <div class={$style.container}>
            {
                optionsList.value.map((option:{[key:string]:any}) => <label class={$style.option + " " + (checkedVal.value == option[valueField.value] ? $style.checked : "")} onClick={() => { change(option[valueField.value]) }}>{option[labelField.value]}</label>)
            }
        </div>
    }
})